package com.example.star.view.setting;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.bumptech.glide.Glide;
import com.example.star.R;
import com.example.star.api_service.ApiUser;
import com.example.star.entity.User;
import com.example.star.retrofit.ApiClient;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class UpdatePasswordActivity extends AppCompatActivity {
    private String username;
    private String password;
    private EditText userName;
    private EditText oldPassword;
    private EditText newPassword;
    private EditText confirmPassword;
    private CheckBox oldPasswordToggle, newPasswordToggle, confirmPasswordToggle;
    private Button sureUpdate;
    private ApiUser userApi;

    @SuppressLint("MissingInflatedId")
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.update_password);
        userName = findViewById(R.id.userName);
        oldPassword = findViewById(R.id.oldPassword);
        newPassword = findViewById(R.id.newPassword);
        confirmPassword = findViewById(R.id.confirmPassword);
        sureUpdate = findViewById(R.id.sureUpdate);
        oldPasswordToggle = findViewById(R.id.oldPasswordToggle);
        newPasswordToggle = findViewById(R.id.newPasswordToggle);
        confirmPasswordToggle = findViewById(R.id.confirmPasswordToggle);

        // 禁止修改用户名
        userName.setEnabled(false);

        // 获取登录页面传递的登录信息
        SharedPreferences sharedPreferences = getSharedPreferences("user_info", Context.MODE_PRIVATE);
        username = sharedPreferences.getString("username", "");
        password = sharedPreferences.getString("loginPassword","");
        getAndDisplayUserInfo(username);

        // 创建 Retrofit 实例
        userApi = ApiClient.getApiUser();

        oldPasswordToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 显示密码
                    oldPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    // 隐藏密码
                    oldPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                oldPassword.setSelection(oldPassword.length()); // 将光标置于文本末尾
            }
        });

        newPasswordToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 显示密码
                    newPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    // 隐藏密码
                    newPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                newPassword.setSelection(newPassword.length()); // 将光标置于文本末尾
            }
        });

        confirmPasswordToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    // 显示密码
                    confirmPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                } else {
                    // 隐藏密码
                    confirmPassword.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                }
                confirmPassword.setSelection(confirmPassword.length()); // 将光标置于文本末尾
            }
        });

        sureUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new AlertDialog.Builder(UpdatePasswordActivity.this)
                        .setMessage("是否确认修改密码")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                updatePassword();
                            }
                        })
                        .setNegativeButton("取消", null)
                        .create()
                        .show();
            }
        });
    }

    private void getAndDisplayUserInfo(String username) {
        ApiUser apiUser = ApiClient.getApiUser();
        apiUser.getUserByUsername(username).enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful() && response.body() != null) {
                    User user = response.body();

                    userName.setText(user.getUsername());

                }
            }
            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(UpdatePasswordActivity.this, "加载信息失败", Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updatePassword() {


        String oldPw = oldPassword.getText().toString().trim();
        String newPw = newPassword.getText().toString().trim();
        String confirmPw = confirmPassword.getText().toString().trim();

        // 基本输入校验
        if (TextUtils.isEmpty(oldPw) || TextUtils.isEmpty(newPw) || TextUtils.isEmpty(confirmPw)) {
            Toast.makeText(this, "所有字段都必须填写", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!password.equals(oldPw)) {
            Toast.makeText(this, "原密码错误", Toast.LENGTH_SHORT).show();
            return;
        }

        if (!newPw.equals(confirmPw)) {
            Toast.makeText(this, "新密码和确认密码不匹配", Toast.LENGTH_SHORT).show();
            return;
        }

        // 发起网络请求
        Call<User> call = userApi.changePassword(username, oldPw, newPw);
        call.enqueue(new Callback<User>() {
            @Override
            public void onResponse(Call<User> call, Response<User> response) {
                if (response.isSuccessful()) {
                    Toast.makeText(UpdatePasswordActivity.this, "修改成功" ,Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    Toast.makeText(UpdatePasswordActivity.this, "修改失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<User> call, Throwable t) {
                Toast.makeText(UpdatePasswordActivity.this, "网络错误: " + t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
}
